#include					"decoder.h"
#include					"byte.h"
#include					<iostream>
#include					<opus/opus.h>

Decoder::Decoder() : _channel(2)
{

}

Decoder::~Decoder()
{

}

void						Decoder::addState(unsigned int id)
{
  int error;
  _dec[id] = opus_decoder_create(48000, _channel, &error);
}

void						Decoder::removeState(unsigned int id)
{
  opus_decoder_destroy(_dec[id]);
}

void						Decoder::decode(Packet *order, SoundPacket *packet, unsigned int id)
{
	int						size = 0;
	short					*datasize = order->getData<short>(1);
	byte					*input = order->getData<byte>(*datasize);
	if (input)
	{
		int						frame_size = opus_decoder_get_nb_samples(_dec[id], input, *datasize);
		int						channel_nb = opus_packet_get_nb_channels(input);

		size =  opus_decode(_dec[id], input, *datasize, packet->data(), frame_size, 0);
		packet->setLen(size * _channel);
		packet->setFS(frame_size);
		packet->current_index = 0;
	}
	else
		std::cout << "[CRITICAL] Audio packet corrupted : can't decode." << std::endl;
	delete datasize;
	delete input;
}
